layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    //新闻列表
    var tableIns = table.render({
        elem: '#taskList',
        // url : '/json/newsList.json',
        url: '/task/list',
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limit: 20,
        limits: [10, 15, 20, 25],
        id: "taskListTable",
        cols: [[
            {type: "checkbox", fixed: "left", width: 50},
            {field: 'jobId', title: 'Job ID', align: "center"},
            {field: 'jobDesc', title: 'Job描述', align: "center"},
            {field: 'cron', title: 'cron表达式', align: 'center'},
            {field: 'handlerName', title: '处理器名', align: 'center'},
            {
                field: 'lockTime', title: '锁定时间', align: 'center', templet: function (d) {
                    return d.lockTime + "s";
                }
            },
            {
                field: 'params', title: '参数', align: 'center', templet: function (d) {
                    return JSON.stringify(d.params);
                }
            },
            {field: 'registerHost', title: '注册地址', align: 'center'},
            {
                field: 'status', title: '状态', align: 'center', templet: function (d) {
                    if (d.status == 0) {
                        return '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" jobId=' + d.jobId + ' registerHost=' + d.registerHost + ' lay-text="UP|DN" ' + '>';
                    } else if (d.status == 1) {
                        return '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" jobId=' + d.jobId + ' registerHost=' + d.registerHost + ' lay-text="UP|DN" checked ' + '>';
                    }

                }
            },
            {title: '操作', width: 170, templet: '#taskListBar', fixed: "right", align: "center"}
        ]]
    });

    //上线、下线
    form.on('switch(status)', function (data) {
        var index = layer.msg('修改中，请稍候', {icon: 16, time: false, shade: 0.8});
        setTimeout(function () {
            let jobId = $(data.elem).attr("jobId")
            let registerHost = $(data.elem).attr("registerHost")
            let status = -1;
            if (data.elem.checked) {
//                 layer.msg("开启成功！");
                status = 1;
            }
            console.log(jobId, registerHost);

            $.post('/task/changeStatus', {jobId: jobId, status: status, registerHost: registerHost}, function (res) {
                layer.close(index);
                if (res.code == 0) {
                    layer.msg('success', {icon: 1})
                } else {
                    layer.msg(res.msg, {icon: 5})
                    console.log(res)
                }

            }, "json")
        }, 500);
    })

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        if ($(".searchVal").val() != '') {
            table.reload("taskListTable", {
                url: '/task/search',
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        } else {
            layer.msg("请输入搜索的内容");
        }
    });

    //修改任务
    function addTask(edit) {
        var index = layui.layer.open({
            title: "修改任务",
            type: 2,
            content: "/page/taskAdd.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".jobId").val(edit.jobId);
                    body.find(".jobDesc").val(edit.jobDesc);
                    body.find(".cron").val(edit.cron);
                    body.find(".handlerName").val(edit.handlerName);
                    body.find(".lockTime").val(edit.lockTime);
                    body.find(".params").val(JSON.stringify(edit.params))
                    body.find(".registerHost").val(edit.registerHost)
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回任务列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    }

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('taskListTable'),
            data = checkStatus.data,
            newsId = [];
        if (data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的任务？(被删除的任务不会被真正删除，而是无法被调用执行)', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        } else {
            layer.msg("请选择需要删除的任务");
        }
    })

    //列表操作
    table.on('tool(taskList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        console.log(data)

        if (layEvent === 'info') { //编辑
            console.log(data);
            addTask(data);
        } else if (layEvent === 'exec') { //删除
            layer.confirm('确定要手动执行？通常只建议在测试时这么做。', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/task/run/" + data.jobId + "/" + data.registerHost, function (data) {
                    tableIns.reload();
                    layer.close(index);
                    if (data.code == 0) {
                        layer.msg("执行成功", {icon: 1})
                    } else {
                        layer.msg("执行失败", {icon: 5})
                    }

                })
            });
        }
    });

})